package com.green.card;

import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.baidu.mobstat.StatService;
import com.green.card.base.BaseActivity;
import com.green.card.constants.Config;
import com.green.card.utils.NetWorkUtils;
import com.green.card.utils.ZYALogUtils;
import com.zhuoyian.pluginsdk.ZYASDKUtil;

import org.apache.http.util.EncodingUtils;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeActivity extends BaseActivity {
    //记录用户首次点击返回键的时间
    private long firstTime = 0;
    //webView控件
    private WebView     mWebView;
    // 根布局
    private LinearLayout mLinearLayoutl;
    //没有网络错误图片
    private ImageButton mIbError;
    //后台配置的推送值
    private String pindKey = "7DB15785AC157B62777FFB427DF890EE";
    private String p;

    /**
     * 初始化view
     */
    public void initView() {
        setContentView(R.layout.activity_home);
        mLinearLayoutl = (LinearLayout) findViewById(R.id.ll);
        mWebView = (WebView) findViewById(R.id.main_web);
        mIbError = (ImageButton) findViewById(R.id.main_ib);
    }

    @Override
    protected void setListener() {

    }

    @Override
    public void initSdk() {
        // 百度统计:建议此代码埋点在统计路径触发的第一个页面中，若可能存在多个则建议都埋点
        baiduStart();
        //启动自家sdk
        initZYASdk();
    }

    @Override
    public void initData() {
        p = getRawFileContent(this, R.raw.p);
        //判断是否有网络连接
        boolean isConnect = NetWorkUtils.isNetworkConnected(this);
        if (isConnect){//当有网络
            okHttpToService(this);
        }else {//没开网络时，加载失败并提示用户打开网络
            toast("当前没有网络连接，点击屏幕现在去打开网络");
            mIbError.setVisibility(View.VISIBLE);
            mWebView.setVisibility(View.GONE);
            //设置点击事件，点击屏幕跳转设置网络
            mLinearLayoutl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
            mIbError.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
        }
    }

    private void baiduStart() {
        //设置渠道号
        StatService.setAppChannel(this,p,true);
        StatService.start(this);
    }


    /**
     * 自家sdk启动
     */
    private void initZYASdk() {
        int packId = Integer.parseInt(p);
        //初始化自家sdk
        ZYASDKUtil.init(this,packId,pindKey,false);
    }

    /**
     * 吐司
     * @param msg
     */
    private void toast(String msg) {
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    /**
     * 使用okHttp请求服务器拿到56卡汇链接
     * @param mainActivity
     */
    private void okHttpToService(final HomeActivity mainActivity) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    //包号
                    String packId = getRawFileContent(mainActivity, R.raw.p);
                    String url = Config.ZYA_URL+"?packId="+packId;
                    ZYALogUtils.d("url-->"+url);
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    final String bankUrl = response.body().string();
                    ZYALogUtils.d("bankUrl-->"+bankUrl);
                    mainActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showWeb(bankUrl);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 展示56卡汇
     * @param bankUrl
     *          银行链接
     */
    private void showWeb(String bankUrl) {
        WebSettings settings = mWebView.getSettings();
        // 显示放大缩小
        settings.setBuiltInZoomControls(true);
        // 设置可以支持缩放
        settings.setSupportZoom(true);
        //为图片添加放大缩小功能
        settings.setUseWideViewPort(true);
        //支持javascript
        settings.setJavaScriptEnabled(true);
        //不显示webview缩放按钮
        settings.setDisplayZoomControls(false);
        if (bankUrl.isEmpty()){
            //如果返回空链接，那么就加载默认的
            mWebView.loadUrl("http://work.zhuoyian.com/Api/card?id=05AD35");
        }else {
            mWebView.loadUrl(bankUrl);
        }
    }


    /**
     * 获取raw目录下的包号
     * @param context
     * @param Id
     * @return
     */
    private static String getRawFileContent(Context context, int Id) {
        String ret = "";
        try {
            InputStream is = context.getResources().openRawResource(Id);
            int len = is.available();
            byte[] buffer = new byte[len];
            is.read(buffer);
            ret = EncodingUtils.getString(buffer, "utf-8");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 按返回键两下退出应用
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                toast("再按一次退出程序");
                firstTime = secondTime;
                return true;
            } else {
                System.exit(0);
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        ZYASDKUtil.destroy(this);

        //webview内存泄露处理
        if( mWebView!=null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再destory()
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }

            mWebView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.clearView();
            mWebView.removeAllViews();
            mWebView.destroy();

        }
        super.onDestroy();
    }
}
